require 'message.rb'


######################################
#
# This file contains the functions that identify and
# handle the various kinds of messages the server
# might send to the bot
#
######################################

class Squick

  # Main wrapper that tries all the others.
  # Returns true if it handled it, false otherwise
  def handleServerMessage(msg, logFile)
     if(handleActualMessage(msg, logFile)) then true
     elsif(handlePartingUser(msg)) then true
     elsif(handleJoiningUser(msg)) then true
     elsif(handleNameList(msg)) then true
     elsif(handleKeepAlive(msg)) then true
     else false
     end
  end

  # This handles/matches messages sent my users (text)
  # and checks them against triggers then displays them
  # to the console
  def handleActualMessage(message, logFile)
    if message.match(/^:(.*)![^ ]* PRIVMSG ([^ ]*) :(.*)$/)
      message = Message.new($~[1], $~[2], $~[3], @nick)
      puts(message.to_s)

      # see if there is anything in the triggers xml
      checkAgainstMessageTriggers(message)

      # Append onto log
      addToLog(message, logFile)
      return true  #indicate that the message was handled
    end
    return false #indicating that is wasn't a message from a user and therefore still needs attention
  end 

  # Pushes "message" onto the logfile
  def addToLog(message, logFilename)
    logFile = File.open(logFilename, "a");
    logFile.puts(message.logOutput())
    logFile.close
  end

  # Matches/handles users joining the channel.
  def handleJoiningUser(msg)
    if msg.match(/^:([^!]*)![^ ]* JOIN :(.*)/) then
      puts("\e[1;32m#{$~[1]}\e[0m has joined #{$~[2]}")
      checkAgainstJoiningTriggers($~[1])
      return true
    end
    return false
  end

  # Matches/handles users leaving the channel
  def handlePartingUser(msg)
    if msg.match(/^:([^!]*)![^ ]* QUIT :(.*)/) then
      puts("\e[1;32m#{$~[1]}\e[0m has quit. (#{$~[2].chop})")
      checkAgainstPartingTriggers($~[1])
      return true
    elsif msg.match(/^:([^!]*)![^ ]* PART (.*)/) then
      puts("\e[1;32m#{$~[1]}\e[0m has left #{$~[2]}.")
      checkAgainstPartingTriggers($~[1])
      return true  
    end
    return false
  end

  # Matches/handles a list of usernames in the channel
  # prints them out to the console
  def handleNameList(msg)
    # if it's an actual list of names, list them out
    if msg.match(/.* = #{@channel} :(.*)/) then
      print "\e[1;36mUsers in #{@channel}:\e[0m "
      $~[1].split(" ").each do |nick|
        print "#{nick} " if (nick.index("@") != 0)
        print "\e[1;32m#{nick}\e[0m " if (nick.index("@") == 0)
      end
      puts
      checkAgainstNamesTriggers($~[1])
      return true
    # if it's the end of list mesage don't display anything
    elsif msg.match(/.* #{@channel} :End of \/NAMES list./)
      return true
    end
    return false
  end
end
